var AudioManager = require('geoAudioManager');
var AudioType = AudioManager.AudioType;

var AudioPlayInfo = cc.Class({
    name: 'geoAudioPlayInfo',
    properties: {
        audioName: {
            default: '',
            tooltip: '音频播放指令的名称，通常对应动画帧标签的名称'
        },
        audioClip: {
            default: null,
            type: cc.AudioClip,
        },
        audioType: {
            default: AudioType.MUSIC,
            type: cc.Enum(AudioType),
            tooltip: '音频类型'
        },
        playTimes: {
            default: 1,
            type: cc.Integer,
            tooltip: '播放次数，-1为无限次数'
        },
        volumn: {
            default: 1,
            type: cc.Float,
        },
        timeStart: {
            default: 0,
            type: cc.Float,
            tooltip: '从音频什么时刻开始播放，小于0皆为从0开始'
        },
        timeEnd: {
            default: 0,
            type: cc.Float,
            tooltip: '结束于音频什么时刻，小于0则为播放到结尾'
        }
    },
});

var AudioStopInfo = cc.Class({
    name: 'geoAudioStopInfo',
    properties:{
        stopName:{
            default:'',
            tooltip:'停止指令名称，通常对应帧动画帧标签名称',
        },
        audioName:{
            default:'',
            tooltip:'要停止的音频播放指令的名称',
        }
    }
})

var AudioPlayGroup = cc.Class({
    extends: cc.Component,

    properties: {
        audios: {
            default: [],
            type: [AudioPlayInfo]
        },
        stops:{
            default:[],
            type: [AudioStopInfo]
        }
    },
    /**
     * 适用于动画帧事件回调的方法
     * @param {*} e 
     * @param {*} com 
     * @param {*} label 
     */
    playAudioOnAnimLabel(e, com, label) {
        this.playAudio(label);
    },
    playStopOnAnimLabel(e, com, label){
        this.playStop(label);
    },
    /**
     * 适用于按钮点击回调
     * @param {*} e 
     * @param {*} com 
     * @param {*} audioName 
     */
    playAudioOnButtonClick(e, audioName) {
        var audio = this.playAudio(audioName);
        return audio;
    },
    playStopOnButtonClick(e, stopName){
        return this.playStop(stopName);
    },
    /**
     * 根据给定的停止指令名停止对应的音频
     * @param {String} stopName 
     */
    playStop(stopName){
        // var stop = null;
        this.stops.some(s => {
            // if (s.stopName == stopName) {
            //     stop = s;
            //     return true;
            // }
            (s.stopName == stopName) && this.stopAudio(s.audioName);
        }, this);
        //
        
        // return stop && this.stopAudio(stop.audioName);
    },
    /**
     * 根据给定的播放指令名播放音频
     * @param {String} audioName 
     * @param {Function} complete 
     */
    playAudio(audioName, complete) {
        var audio = this.stopAudio(audioName);
        audio && this._playAudioInternal(audio, complete);
        audio && (audio._isPaused = false);
        return audio;
    },
    stopAudio(audioName) {
        var audio = this.findAudio(audioName);
        if (audio && audio._audioPlayID != null) {
            AudioManager.Singleton.stopAudio(audio._audioPlayID);
            audio._audioPlayID = null;
        }
        if (audio && audio._loopAudioSchedule != null) {
            this.unschedule(audio._loopAudioSchedule);
            audio._loopAudioSchedule = null;
        }
        return audio;
    },
    pauseAudio(audioName) {
        var audio = this.findAudio(audioName);
        if (audio && audio._audioPlayID != null) {
            AudioManager.Singleton.pauseAudio(audio._audioPlayID);
            audio._isPaused = true;
            // 停止时间回调
            if (audio._loopAudioSchedule != null) {
                cc.log('unchedule on pause');
                this.unschedule(audio._loopAudioSchedule);
            }
            if (audio._resumeAudioSchedule != null) {
                this.unschedule(audio._resumeAudioSchedule);
            }
        }
        return audio;
    },
    resumeAudio(audioName) {
        var audio = this.findAudio(audioName);
        if (audio && audio._audioPlayID != null && audio._isPaused == true) {
            audio._isPaused = false;
            AudioManager.Singleton.resumeAudio(audio._audioPlayID);
            if (audio._loopAudioSchedule != null) {
                // 获取当前播放时间
                var curTime = cc.audioEngine.getCurrentTime(audio._audioPlayID);
                audio._needReschedule = true;
                // 恢复时间回调
                cc.log('chedule on resume');
                this.scheduleOnce(audio._resumeAudioSchedule, audio._timeEnd - curTime);
            }
        }
        return audio;
    },
    findAudio(audioName) {
        var audio = null;
        this.audios.some(a => {
            if (a.audioName == audioName) {
                audio = a;
                return true;
            }
        });
        //
        return audio;
    },
    stopAllAudios() {
        this.audios.forEach(audio => {
            this.stopAudio(audio.audioName);
        });
    },
    _playAudioInternal(audio, complete) {
        var self = this;
        // 只要playTimes不是1，就设定为循环播放，次数由后面处理
        var loops = (audio.playTimes != 1) ? true : false;
        // 播放
        var audioID = AudioManager.Singleton.play(audio.audioType, audio.audioClip, loops, audio.volumn);
        // 处理播放时段
        var dur = cc.audioEngine.getDuration(audioID);
        var timeStart = audio.timeStart;
        var timeEnd = audio.timeEnd;
        // 修正开始时间
        (timeStart < 0 || timeStart > dur) && (timeStart = 0);
        // 修正结束时间
        (timeEnd <= timeStart || timeEnd > dur) && (timeEnd = dur);
        // 记录播放id
        audio._audioPlayID = audioID;
        // 开启正式第一次播放
        cc.audioEngine.setCurrentTime(audio._audioPlayID, timeStart);
        // 记录设定
        // audio._timeStart = timeStart;
        audio._timeEnd = timeEnd;
        let loopTime = timeEnd - timeStart;
        // 设定已经播放过的次数
        audio._numLoopsPlayed = 0;
        //
        audio._loopAudioSchedule = () => {
            // 累计播放次数
            audio._numLoopsPlayed++;
            cc.log('numloopsplayed: ' + audio._numLoopsPlayed);
            //
            // cc.log('numLoopsPlayed: ' + audio._numLoopsPlayed);
            // 是否已经达到最大播放次数，并尝试回调结束
            if (audio.playTimes > 0 && audio._numLoopsPlayed == audio.playTimes) {
                self.stopAudio(audio.audioName);
                complete && complete();
            } else {
                // 重新设置时间
                cc.audioEngine.setCurrentTime(audio._audioPlayID, timeStart);
                // 启动定时器
                // self.unschedule(audio._loopAudioSchedule);
                if (audio._needReschedule == true)
                    self.schedule(audio._loopAudioSchedule, loopTime, cc.macro.REPEAT_FOREVER, loopTime);
                audio._needReschedule = false;
            }
        };
        audio._resumeAudioSchedule = () => {
            audio._loopAudioSchedule();
        };
        // 启动定时器
        self.schedule(audio._loopAudioSchedule, loopTime, cc.macro.REPEAT_FOREVER, loopTime);
    }
});

module.exports = AudioPlayGroup;
